package me.android.library.common.service.monitor;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;

import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.android.library.utils.android.ContextUtil;

/**
 * 连接监控服务实现类
 * 实现了所有连接监控接口的具体功能
 */
@SuppressLint(value = {"MissingPermission","ObsoleteSdkInt"})
public class ConnectionMonitorServiceImpl implements
        ConnectionMonitor,
        BluetoothConnectionMonitor,
        WifiP2pConnectionMonitor {

    private static final String TAG = "ConnMonitorImpl";
    public static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "CONNECTION_MONITOR_CHANNEL";
    private static final String CHANNEL_NAME = "连接监控服务";

    // 存储相关常量
    private static final String PREFS_NAME = "ConnectionMonitorPrefs";
    private static final String KEY_LAST_BT_DEVICE_ADDRESS = "last_bt_device_address";
    private static final String KEY_LAST_BT_DEVICE_NAME = "last_bt_device_name";
    private static final String KEY_LAST_WIFI_DEVICE_ADDRESS = "last_wifi_device_address";
    private static final String KEY_LAST_WIFI_DEVICE_NAME = "last_wifi_device_name";

    // 扫描相关常量
    private static final long SCAN_TIMEOUT = 15000; // 扫描超时时间(ms)

    // 重连配置
    private static final int MIN_RECONNECT_DELAY = 1000; // 最小重连延迟(ms)
    private static final int MAX_RECONNECT_DELAY = 30000; // 最大重连延迟(ms)
    private static final int RECONNECT_BACKOFF_FACTOR = 2; // 重连延迟倍数

    private final Context context;
    private ServiceState serviceState = ServiceState.STOPPED;

    // 监听器集合
    private final Set<ConnectionStatusListener> connectionStatusListeners = new HashSet<>();
    private final Set<BluetoothScanListener> bluetoothScanListeners = new HashSet<>();
    private final Set<WifiP2pScanListener> wifiP2pScanListeners = new HashSet<>();

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    private BluetoothDevice targetBluetoothDevice;
    private boolean isBluetoothConnected = false;
    private boolean isBluetoothScanning = false;

    // WiFi P2P相关
    private WifiP2pManager wifiP2pManager;
    private WifiP2pManager.Channel wifiP2pChannel;
    private WifiP2pDevice targetWifiP2pDevice;
    private boolean isWifiP2pConnected = false;
    private boolean isWifiP2pScanning = false;
    private final List<WifiP2pDevice> wifiP2pDevices = new ArrayList<>();

    // 重连延迟跟踪
    private final Map<ConnectionType, Integer> reconnectDelays = new HashMap<>();

    // 后台处理
    private HandlerThread backgroundThread;
    private Handler backgroundHandler;
    private Handler mainHandler;

    // 存储
    private SharedPreferences sharedPreferences;

    // 通知管理器
    private NotificationManagerCompat notificationManager;

    public ConnectionMonitorServiceImpl(Context context) {
        this.context = context.getApplicationContext();
        init();
    }

    /**
     * 初始化服务
     */
    private void init() {
        // 初始化通知管理器
        notificationManager = NotificationManagerCompat.from(context);

        // 初始化存储
        sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        // 初始化Handler
        mainHandler = new Handler(Looper.getMainLooper());
        backgroundThread = new HandlerThread("ConnectionMonitorThread");
        backgroundThread.start();
        backgroundHandler = new Handler(backgroundThread.getLooper());

        // 初始化重连延迟
        reconnectDelays.put(ConnectionType.BLUETOOTH, MIN_RECONNECT_DELAY);
        reconnectDelays.put(ConnectionType.WIFI_P2P, MIN_RECONNECT_DELAY);

        // 初始化蓝牙
        // 蓝牙相关
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager != null) {
            bluetoothAdapter = bluetoothManager.getAdapter();
            if (bluetoothAdapter != null) {
                bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            }
        }

        // 初始化WiFi P2P
        wifiP2pManager = (WifiP2pManager) context.getSystemService(Context.WIFI_P2P_SERVICE);
        if (wifiP2pManager != null) {
            wifiP2pChannel = wifiP2pManager.initialize(context, Looper.getMainLooper(), null);
        }

        // 注册广播接收器
        registerBroadcastReceivers();
    }

    /**
     * 创建通知渠道（Android O+）
     */
    private void createNotificationChannel() {
        // 仅在Android O（API 26）及以上版本需要创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知渠道构建器
            NotificationChannelCompat.Builder channelBuilder = new NotificationChannelCompat.Builder(
                    CHANNEL_ID,
                    NotificationManagerCompat.IMPORTANCE_LOW
            );

            // 设置渠道名称和描述
            channelBuilder.setName(CHANNEL_NAME);
            channelBuilder.setDescription("监控蓝牙和WiFi P2P连接状态，支持自动重连");

            // 构建通知渠道
            NotificationChannelCompat channel = channelBuilder.build();

            // 通过NotificationManagerCompat创建渠道
            NotificationManagerCompat.from(ContextUtil.getAppContext()).createNotificationChannel(channel);
        }
    }

    /**
     * 创建前台服务通知
     */
    public Notification createNotification() {
        createNotificationChannel();

        // 创建不依赖具体Activity的意图，启动应用的主Activity
        Intent notificationIntent = getLaunchIntentForApp();
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                0,
                notificationIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );

        // 构建通知内容
        String contentText = "监控中";
        if (targetBluetoothDevice != null) {
            contentText += " - 蓝牙目标: " + (targetBluetoothDevice.getName() != null ?
                    targetBluetoothDevice.getName() : targetBluetoothDevice.getAddress());
        }
        if (targetWifiP2pDevice != null) {
            contentText += " - WiFi P2P目标: " + (targetWifiP2pDevice.deviceName != null ?
                    targetWifiP2pDevice.deviceName : targetWifiP2pDevice.deviceAddress);
        }

        return new NotificationCompat.Builder(context, CHANNEL_ID)
                .setContentTitle("连接监控服务")
                .setContentText(contentText)
                .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth) // 使用系统图标，实际项目中替换为自己的图标
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setOngoing(true)
                .build();
    }

    /**
     * 更新通知内容
     */
    private void updateNotification() {
        Notification notification = createNotification();
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 获取应用的启动意图，不依赖具体Activity
     */
    private Intent getLaunchIntentForApp() {
        // 获取应用的主启动意图
        PackageManager packageManager = context.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());

        if (intent != null) {
            // 设置标志确保启动新任务
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                    Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            return intent;
        }

        // 作为备选，创建一个打开应用的意图
        return new Intent(Intent.ACTION_MAIN)
                .addCategory(Intent.CATEGORY_LAUNCHER)
                .setPackage(context.getPackageName())
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 注册广播接收器
     */
    private void registerBroadcastReceivers() {
        // 注册蓝牙广播接收器
        IntentFilter bluetoothFilter = new IntentFilter();
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        bluetoothFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        bluetoothFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        context.registerReceiver(bluetoothReceiver, bluetoothFilter);

        // 注册WiFi P2P广播接收器
        IntentFilter wifiP2pFilter = new IntentFilter();
        wifiP2pFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        wifiP2pFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        context.registerReceiver(wifiP2pReceiver, wifiP2pFilter);
    }

    /**
     * 注销广播接收器
     */
    private void unregisterBroadcastReceivers() {
        try {
            context.unregisterReceiver(bluetoothReceiver);
            context.unregisterReceiver(wifiP2pReceiver);
        } catch (Exception e) {
            Log.e(TAG, "注销广播接收器失败", e);
        }
    }

    // 蓝牙广播接收器
    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;

            // 蓝牙状态变化
            switch (action) {
                case BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                    Log.d(TAG, "蓝牙状态变化: " + getBluetoothStateString(state));

                    if (state == BluetoothAdapter.STATE_ON) {
                        // 蓝牙已开启，尝试连接上次的设备
                        connectLastKnownBluetoothDevice();
                    }
                }
                // 蓝牙连接状态变化
                case BluetoothDevice.ACTION_ACL_CONNECTED -> {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    assert device != null;
                    Log.d(TAG, "蓝牙已连接: " + device.getName() + " (" + device.getAddress() + ")");

                    isBluetoothConnected = true;
                    resetReconnectDelay(ConnectionType.BLUETOOTH);

                    // 如果是目标设备，保存信息
                    if (targetBluetoothDevice != null &&
                            device.getAddress().equals(targetBluetoothDevice.getAddress())) {
                        saveBluetoothDevice(device);
                    }

                    // 通知连接状态变化
                    notifyConnectionStatusChanged(ConnectionType.BLUETOOTH, true,
                            device.getName() != null ? device.getName() : device.getAddress());
                }

                // 蓝牙断开连接
                case BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    assert device != null;
                    Log.d(TAG, "蓝牙已断开: " + device.getName() + " (" + device.getAddress() + ")");

                    isBluetoothConnected = false;

                    // 通知连接状态变化
                    notifyConnectionStatusChanged(ConnectionType.BLUETOOTH, false,
                            device.getName() != null ? device.getName() : device.getAddress());

                    // 如果是目标设备且服务运行中，尝试重连
                    if (targetBluetoothDevice != null && device.getAddress().equals(targetBluetoothDevice.getAddress())
                            && serviceState == ServiceState.RUNNING) {
                        scheduleBluetoothReconnect();
                    }
                }
            }
        }
    };

    // WiFi P2P广播接收器
    private final BroadcastReceiver wifiP2pReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;

            // WiFi P2P连接状态变化
            if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
                if (wifiP2pManager == null) return;

                // 获取连接信息
                wifiP2pManager.requestConnectionInfo(wifiP2pChannel, connectionInfo -> {
                    if (connectionInfo != null && connectionInfo.groupOwnerAddress != null) {
                        isWifiP2pConnected = true;
                        resetReconnectDelay(ConnectionType.WIFI_P2P);

                        // 找到对应的设备名称
                        String deviceName = "未知设备";
                        if (targetWifiP2pDevice != null) {
                            deviceName = targetWifiP2pDevice.deviceName;
                            saveWifiP2pDevice(targetWifiP2pDevice);
                        }

                        Log.d(TAG, "WiFi P2P连接成功: " + deviceName);
                        notifyConnectionStatusChanged(ConnectionType.WIFI_P2P, true, deviceName);
                    } else {
                        isWifiP2pConnected = false;
                        Log.d(TAG, "WiFi P2P已断开");

                        String deviceName = "未知设备";
                        if (targetWifiP2pDevice != null) {
                            deviceName = targetWifiP2pDevice.deviceName;
                        }

                        notifyConnectionStatusChanged(ConnectionType.WIFI_P2P, false, deviceName);

                        // 如果断开连接且服务运行中，尝试重连
                        if (targetWifiP2pDevice != null && serviceState == ServiceState.RUNNING) {
                            scheduleWifiP2pReconnect();
                        }
                    }
                });
            }
            // WiFi P2P设备列表变化
            else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                if (wifiP2pManager != null && wifiP2pChannel != null) {
                    // 请求最新的设备列表
                    wifiP2pManager.requestPeers(wifiP2pChannel, peerListListener);
                }
            }
        }
    };

    // WiFi P2P设备列表监听器
    private final WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peers) {
            List<WifiP2pDevice> refreshedDevices = new ArrayList<>(peers.getDeviceList());
            if (!refreshedDevices.equals(wifiP2pDevices)) {
                wifiP2pDevices.clear();
                wifiP2pDevices.addAll(refreshedDevices);

                // 通知新设备发现
                for (WifiP2pDevice device : refreshedDevices) {
                    if (device.status == WifiP2pDevice.AVAILABLE ||
                            device.status == WifiP2pDevice.INVITED) {
                        notifyWifiP2pDeviceFound(device);
                    }
                }
            }

            // 如果扫描已超时，停止扫描
            if (isWifiP2pScanning && backgroundHandler != null) {
                backgroundHandler.postDelayed(() -> stopWifiP2pScan(), SCAN_TIMEOUT);
            }
        }
    };

    // 蓝牙LE扫描回调
    private final ScanCallback bluetoothLeScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            if (result != null && result.getDevice() != null) {
                BluetoothDevice device = result.getDevice();
                Log.d(TAG, "发现蓝牙设备: " + device.getName() + " (" + device.getAddress() + ")");
                notifyBluetoothDeviceFound(device);
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            for (ScanResult result : results) {
                if (result != null && result.getDevice() != null) {
                    BluetoothDevice device = result.getDevice();
                    notifyBluetoothDeviceFound(device);
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "蓝牙扫描失败，错误码: " + errorCode);
            isBluetoothScanning = false;
            notifyBluetoothScanError(errorCode);
        }
    };

    //region ConnectionMonitor接口实现
    @Override
    public void startMonitoring() {
        if (serviceState != ServiceState.STOPPED) {
            return;
        }

        serviceState = ServiceState.RUNNING;
        Log.d(TAG, "开始监控服务");

        // 尝试连接上次保存的设备
        connectLastKnownDevices();
    }

    @Override
    public void stopMonitoring() {
        if (serviceState == ServiceState.STOPPED) {
            return;
        }

        serviceState = ServiceState.STOPPED;
        Log.d(TAG, "停止监控服务");

        // 停止所有扫描
        stopBluetoothScan();
        stopWifiP2pScan();

        // 取消所有重连任务
        if (backgroundHandler != null) {
            backgroundHandler.removeCallbacksAndMessages(null);
        }

        // 注销广播接收器
        unregisterBroadcastReceivers();

        // 停止后台线程
        if (backgroundThread != null) {
            backgroundThread.quitSafely();
        }
    }

    @Override
    public void pauseMonitoring() {
        if (serviceState == ServiceState.RUNNING) {
            serviceState = ServiceState.PAUSED;
            backgroundHandler.removeCallbacksAndMessages(null);
            Log.d(TAG, "监控已暂停");
        }
    }

    @Override
    public void resumeMonitoring() {
        if (serviceState == ServiceState.PAUSED) {
            serviceState = ServiceState.RUNNING;
            Log.d(TAG, "监控已恢复");

            // 检查并尝试重连
            if (!isBluetoothConnected && targetBluetoothDevice != null) {
                attemptBluetoothReconnect();
            }

            if (!isWifiP2pConnected && targetWifiP2pDevice != null) {
                attemptWifiP2pReconnect();
            }
        }
    }

    @Override
    public ServiceState getServiceState() {
        return serviceState;
    }

    @Override
    public void addConnectionStatusListener(ConnectionStatusListener listener) {
        if (listener != null) {
            connectionStatusListeners.add(listener);
        }
    }

    @Override
    public void removeConnectionStatusListener(ConnectionStatusListener listener) {
        if (listener != null) {
            connectionStatusListeners.remove(listener);
        }
    }

    /**
     * 通知连接状态变化
     */
    private void notifyConnectionStatusChanged(ConnectionType type, boolean isConnected, String deviceName) {
        // 更新通知
        updateNotification();

        // 通知所有监听器
        for (ConnectionStatusListener listener : new HashSet<>(connectionStatusListeners)) {
            mainHandler.post(() ->
                    listener.onConnectionStateChanged(type, isConnected, deviceName)
            );
        }
    }
    //endregion

    //region BluetoothConnectionMonitor接口实现
    @Override
    public void startBluetoothScan() {
        if (isBluetoothScanning || bluetoothAdapter == null || bluetoothLeScanner == null) {
            return;
        }

        // 确保蓝牙已开启
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
            // 延迟后再开始扫描，等待蓝牙开启
            backgroundHandler.postDelayed(this::startBluetoothScan, 1000);
            return;
        }

        Log.d(TAG, "开始蓝牙设备扫描");
        isBluetoothScanning = true;

        // 配置扫描参数
        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                .build();

        // 可以添加过滤条件，如特定UUID的设备
        List<ScanFilter> filters = new ArrayList<>();

        // 开始扫描
        bluetoothLeScanner.startScan(filters, settings, bluetoothLeScanCallback);

        // 设置扫描超时
        backgroundHandler.postDelayed(() -> {
            stopBluetoothScan();
            notifyBluetoothScanFinished();
        }, SCAN_TIMEOUT);
    }

    @Override
    public void stopBluetoothScan() {
        if (!isBluetoothScanning || bluetoothLeScanner == null) {
            return;
        }

        Log.d(TAG, "停止蓝牙设备扫描");
        isBluetoothScanning = false;
        bluetoothLeScanner.stopScan(bluetoothLeScanCallback);
    }

    @Override
    public void setTargetBluetoothDevice(BluetoothDevice device) {
        this.targetBluetoothDevice = device;
        String deviceName = device.getName() != null ? device.getName() : device.getAddress();
        Log.d(TAG, "已设置目标蓝牙设备: " + deviceName);

        // 保存设备信息
        saveBluetoothDevice(device);

        // 更新通知
        updateNotification();

        // 立即检查连接状态
        checkBluetoothConnectionStatus();

        // 如果未连接且服务运行中，尝试连接
        if (!isBluetoothConnected && serviceState == ServiceState.RUNNING) {
            attemptBluetoothReconnect();
        }
    }

    @Override
    public BluetoothDevice getTargetBluetoothDevice() {
        return targetBluetoothDevice;
    }

    @Override
    public void clearBluetoothDeviceInfo() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_LAST_BT_DEVICE_ADDRESS);
        editor.remove(KEY_LAST_BT_DEVICE_NAME);
        editor.apply();

        targetBluetoothDevice = null;
        updateNotification();
    }

    @Override
    public boolean isBluetoothConnected() {
        return isBluetoothConnected;
    }

    @Override
    public void addBluetoothScanListener(BluetoothScanListener listener) {
        if (listener != null) {
            bluetoothScanListeners.add(listener);
        }
    }

    @Override
    public void removeBluetoothScanListener(BluetoothScanListener listener) {
        if (listener != null) {
            bluetoothScanListeners.remove(listener);
        }
    }

    /**
     * 通知发现蓝牙设备
     */
    private void notifyBluetoothDeviceFound(BluetoothDevice device) {
        for (BluetoothScanListener listener : new HashSet<>(bluetoothScanListeners)) {
            mainHandler.post(() -> listener.onBluetoothDeviceFound(device));
        }
    }

    /**
     * 通知蓝牙扫描完成
     */
    private void notifyBluetoothScanFinished() {
        for (BluetoothScanListener listener : new HashSet<>(bluetoothScanListeners)) {
            mainHandler.post(listener::onBluetoothScanFinished);
        }
    }

    /**
     * 通知蓝牙扫描错误
     */
    private void notifyBluetoothScanError(int errorCode) {
        for (BluetoothScanListener listener : new HashSet<>(bluetoothScanListeners)) {
            mainHandler.post(() -> listener.onBluetoothScanError(errorCode));
        }
    }

    /**
     * 检查蓝牙连接状态
     */
    private void checkBluetoothConnectionStatus() {
        if (bluetoothAdapter == null || targetBluetoothDevice == null) return;

        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : bondedDevices) {
            if (device.getAddress().equals(targetBluetoothDevice.getAddress())) {
                isBluetoothConnected = true;
                return;
            }
        }
        isBluetoothConnected = false;
    }

    /**
     * 尝试蓝牙重连
     */
    private void attemptBluetoothReconnect() {
        if (bluetoothAdapter == null || targetBluetoothDevice == null) return;

        backgroundHandler.post(() -> {
            String deviceName = targetBluetoothDevice.getName() != null ?
                    targetBluetoothDevice.getName() : targetBluetoothDevice.getAddress();
            Log.d(TAG, "尝试连接蓝牙设备: " + deviceName);

            // 确保蓝牙已开启
            if (!bluetoothAdapter.isEnabled()) {
                Log.d(TAG, "正在开启蓝牙...");
                bluetoothAdapter.enable();
                return;
            }

            // 实际连接逻辑 - 根据设备类型实现
            boolean connectionInitiated = initiateBluetoothConnection(targetBluetoothDevice);

            if (!connectionInitiated) {
                Log.d(TAG, "蓝牙连接发起失败，将重试");
                scheduleBluetoothReconnect();
            }
        });
    }

    /**
     * 发起蓝牙连接
     */
    private boolean initiateBluetoothConnection(BluetoothDevice device) {
        try {
            // 对于BLE设备，使用GATT连接
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                device.connectGatt(context, false, new BluetoothGattCallback() {
                    @Override
                    public void onConnectionStateChange(android.bluetooth.BluetoothGatt gatt, int status, int newState) {
                        super.onConnectionStateChange(gatt, status, newState);
                        if (newState == android.bluetooth.BluetoothGatt.STATE_CONNECTED) {
                            Log.d(TAG, "BLE设备连接成功");
                            gatt.discoverServices();
                        } else if (newState == android.bluetooth.BluetoothGatt.STATE_DISCONNECTED) {
                            Log.d(TAG, "BLE设备连接断开");
                            gatt.close();
                            if (serviceState == ServiceState.RUNNING) {
                                scheduleBluetoothReconnect();
                            }
                        }
                    }
                }, BluetoothDevice.TRANSPORT_LE);
                return true;
            }

            return true;
        } catch (Exception e) {
            Log.e(TAG, "蓝牙连接失败", e);
            return false;
        }
    }
    //endregion

    //region WifiP2pConnectionMonitor接口实现
    @Override
    public void startWifiP2pScan() {
        if (isWifiP2pScanning || wifiP2pManager == null || wifiP2pChannel == null) {
            return;
        }

        Log.d(TAG, "开始WiFi P2P设备扫描");
        isWifiP2pScanning = true;
        wifiP2pDevices.clear();

        wifiP2pManager.discoverPeers(wifiP2pChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "WiFi P2P扫描已启动");
                // 设置扫描超时
                backgroundHandler.postDelayed(() -> {
                    stopWifiP2pScan();
                    notifyWifiP2pScanFinished();
                }, SCAN_TIMEOUT);
            }

            @Override
            public void onFailure(int reason) {
                Log.e(TAG, "WiFi P2P扫描启动失败，原因: " + reason);
                isWifiP2pScanning = false;
                notifyWifiP2pScanError(reason);
            }
        });
    }

    @Override
    public void stopWifiP2pScan() {
        if (!isWifiP2pScanning) {
            return;
        }

        Log.d(TAG, "停止WiFi P2P设备扫描");
        isWifiP2pScanning = false;
    }

    @Override
    public void setTargetWifiP2pDevice(WifiP2pDevice device) {
        this.targetWifiP2pDevice = device;
        String deviceName = device.deviceName != null ? device.deviceName : device.deviceAddress;
        Log.d(TAG, "已设置目标WiFi P2P设备: " + deviceName);

        // 保存设备信息
        saveWifiP2pDevice(device);

        // 更新通知
        updateNotification();

        // 如果未连接且服务运行中，尝试连接
        if (!isWifiP2pConnected && serviceState == ServiceState.RUNNING) {
            attemptWifiP2pReconnect();
        }
    }

    @Override
    public WifiP2pDevice getTargetWifiP2pDevice() {
        return targetWifiP2pDevice;
    }

    @Override
    public void clearWifiP2pDeviceInfo() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_LAST_WIFI_DEVICE_ADDRESS);
        editor.remove(KEY_LAST_WIFI_DEVICE_NAME);
        editor.apply();

        targetWifiP2pDevice = null;
        updateNotification();
    }

    @Override
    public boolean isWifiP2pConnected() {
        return isWifiP2pConnected;
    }

    @Override
    public void addWifiP2pScanListener(WifiP2pScanListener listener) {
        if (listener != null) {
            wifiP2pScanListeners.add(listener);
        }
    }

    @Override
    public void removeWifiP2pScanListener(WifiP2pScanListener listener) {
        if (listener != null) {
            wifiP2pScanListeners.remove(listener);
        }
    }

    /**
     * 通知发现WiFi P2P设备
     */
    private void notifyWifiP2pDeviceFound(WifiP2pDevice device) {
        for (WifiP2pScanListener listener : new HashSet<>(wifiP2pScanListeners)) {
            mainHandler.post(() -> listener.onWifiP2pDeviceFound(device));
        }
    }

    /**
     * 通知WiFi P2P扫描完成
     */
    private void notifyWifiP2pScanFinished() {
        for (WifiP2pScanListener listener : new HashSet<>(wifiP2pScanListeners)) {
            mainHandler.post(listener::onWifiP2pScanFinished);
        }
    }

    /**
     * 通知WiFi P2P扫描错误
     */
    private void notifyWifiP2pScanError(int errorCode) {
        for (WifiP2pScanListener listener : new HashSet<>(wifiP2pScanListeners)) {
            mainHandler.post(() -> listener.onWifiP2pScanError(errorCode));
        }
    }

    /**
     * 尝试WiFi P2P重连
     */
    private void attemptWifiP2pReconnect() {
        if (wifiP2pManager == null || wifiP2pChannel == null || targetWifiP2pDevice == null) return;

        backgroundHandler.post(() -> {
            String deviceName = targetWifiP2pDevice.deviceName != null ?
                    targetWifiP2pDevice.deviceName : targetWifiP2pDevice.deviceAddress;
            Log.d(TAG, "尝试连接WiFi P2P设备: " + deviceName);

            WifiP2pConfig config = new WifiP2pConfig();
            config.deviceAddress = targetWifiP2pDevice.deviceAddress;
            config.wps.setup = WpsInfo.PBC; // 根据实际需求选择WPS模式

            wifiP2pManager.connect(wifiP2pChannel, config, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    Log.d(TAG, "WiFi P2P连接请求已发送");
                }

                @Override
                public void onFailure(int reason) {
                    Log.d(TAG, "WiFi P2P连接请求失败，原因: " + reason);
                    scheduleWifiP2pReconnect();
                }
            });
        });
    }
    //endregion

    //region 重连调度相关方法
    /**
     * 安排蓝牙重连（使用指数退避算法）
     */
    private void scheduleBluetoothReconnect() {
        int currentDelay = reconnectDelays.get(ConnectionType.BLUETOOTH);
        Log.d(TAG, "将在 " + currentDelay + "ms 后尝试蓝牙重连");

        backgroundHandler.postDelayed(() -> {
            if (serviceState == ServiceState.RUNNING && !isBluetoothConnected) {
                attemptBluetoothReconnect();
                // 增加下次重连延迟，最多不超过最大值
                int nextDelay = Math.min(currentDelay * RECONNECT_BACKOFF_FACTOR, MAX_RECONNECT_DELAY);
                reconnectDelays.put(ConnectionType.BLUETOOTH, nextDelay);
            }
        }, currentDelay);
    }

    /**
     * 安排WiFi P2P重连（使用指数退避算法）
     */
    private void scheduleWifiP2pReconnect() {
        int currentDelay = reconnectDelays.get(ConnectionType.WIFI_P2P);
        Log.d(TAG, "将在 " + currentDelay + "ms 后尝试WiFi P2P重连");

        backgroundHandler.postDelayed(() -> {
            if (serviceState == ServiceState.RUNNING && !isWifiP2pConnected) {
                attemptWifiP2pReconnect();
                // 增加下次重连延迟，最多不超过最大值
                int nextDelay = Math.min(currentDelay * RECONNECT_BACKOFF_FACTOR, MAX_RECONNECT_DELAY);
                reconnectDelays.put(ConnectionType.WIFI_P2P, nextDelay);
            }
        }, currentDelay);
    }

    /**
     * 重置重连延迟
     */
    private void resetReconnectDelay(ConnectionType type) {
        reconnectDelays.put(type, MIN_RECONNECT_DELAY);
    }
    //endregion

    //region 设备存储和恢复相关方法
    /**
     * 保存蓝牙设备信息
     */
    private void saveBluetoothDevice(BluetoothDevice device) {
        if (device == null) return;

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_LAST_BT_DEVICE_ADDRESS, device.getAddress());
        editor.putString(KEY_LAST_BT_DEVICE_NAME, device.getName());
        editor.apply();
        Log.d(TAG, "已保存蓝牙设备信息: " + (device.getName() != null ? device.getName() : device.getAddress()));
    }

    /**
     * 保存WiFi P2P设备信息
     */
    private void saveWifiP2pDevice(WifiP2pDevice device) {
        if (device == null) return;

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_LAST_WIFI_DEVICE_ADDRESS, device.deviceAddress);
        editor.putString(KEY_LAST_WIFI_DEVICE_NAME, device.deviceName);
        editor.apply();
        Log.d(TAG, "已保存WiFi P2P设备信息: " + (device.deviceName != null ? device.deviceName : device.deviceAddress));
    }

    /**
     * 连接上次保存的所有设备
     */
    private void connectLastKnownDevices() {
        connectLastKnownBluetoothDevice();
        connectLastKnownWifiP2pDevice();
    }

    /**
     * 连接上次保存的蓝牙设备
     */
    private void connectLastKnownBluetoothDevice() {
        if (bluetoothAdapter == null) return;

        String address = sharedPreferences.getString(KEY_LAST_BT_DEVICE_ADDRESS, null);
        String name = sharedPreferences.getString(KEY_LAST_BT_DEVICE_NAME, null);

        if (address != null) {
            try {
                BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
                if (device != null) {
                    targetBluetoothDevice = device;
                    Log.d(TAG, "找到上次连接的蓝牙设备: " + (name != null ? name : address));
                    updateNotification();

                    if (serviceState == ServiceState.RUNNING && !isBluetoothConnected) {
                        attemptBluetoothReconnect();
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取上次连接的蓝牙设备失败", e);
                // 清除无效的设备信息
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.remove(KEY_LAST_BT_DEVICE_ADDRESS);
                editor.remove(KEY_LAST_BT_DEVICE_NAME);
                editor.apply();
            }
        }
    }

    /**
     * 连接上次保存的WiFi P2P设备
     */
    private void connectLastKnownWifiP2pDevice() {
        String address = sharedPreferences.getString(KEY_LAST_WIFI_DEVICE_ADDRESS, null);
        String name = sharedPreferences.getString(KEY_LAST_WIFI_DEVICE_NAME, null);

        if (address != null && wifiP2pManager != null && wifiP2pChannel != null) {
            Log.d(TAG, "尝试查找上次连接的WiFi P2P设备: " + (name != null ? name : address));

            // 开始扫描以找到设备
            startWifiP2pScan();

            // 扫描一段时间后尝试连接
            backgroundHandler.postDelayed(() -> {
                for (WifiP2pDevice device : wifiP2pDevices) {
                    if (address.equals(device.deviceAddress)) {
                        targetWifiP2pDevice = device;
                        Log.d(TAG, "找到上次连接的WiFi P2P设备: " + (name != null ? name : address));
                        updateNotification();

                        if (serviceState == ServiceState.RUNNING && !isWifiP2pConnected) {
                            attemptWifiP2pReconnect();
                        }
                        break;
                    }
                }
            }, SCAN_TIMEOUT / 2);
        }
    }
    //endregion

    /**
     * 将蓝牙状态码转换为字符串
     */
    private String getBluetoothStateString(int state) {
        return switch (state) {
            case BluetoothAdapter.STATE_OFF -> "已关闭";
            case BluetoothAdapter.STATE_TURNING_ON -> "正在开启";
            case BluetoothAdapter.STATE_ON -> "已开启";
            case BluetoothAdapter.STATE_TURNING_OFF -> "正在关闭";
            default -> "未知状态: " + state;
        };
    }
}
